<template>
  <div class="vehicle-management">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item label="车牌号">
          <el-input
            v-model="searchForm.licensePlate"
            placeholder="请输入车牌号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="车辆类型">
          <el-select
            v-model="searchForm.vehicleType"
            placeholder="请选择车辆类型"
            clearable
            style="width: 150px"
          >
            <el-option label="小型汽车" :value="1" />
            <el-option label="大型汽车" :value="2" />
            <el-option label="摩托车" :value="3" />
            <el-option label="电动车" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆状态">
          <el-select
            v-model="searchForm.vehicleStatus"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
            <el-option label="黑名单" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="认证状态">
          <el-select
            v-model="searchForm.verificationStatus"
            placeholder="请选择认证状态"
            clearable
            style="width: 120px"
          >
            <el-option label="未认证" :value="0" />
            <el-option label="已认证" :value="1" />
            <el-option label="认证失败" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加车辆
        </el-button>
        <el-button type="success" @click="handleBatchImport">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="filteredTableData"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="licensePlate" label="车牌号" width="120" />
        <el-table-column prop="vehicleTypeName" label="车辆类型" width="100" />
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column prop="model" label="型号" width="120" />
        <el-table-column prop="color" label="颜色" width="80" />
        <el-table-column prop="vehicleStatusName" label="状态" width="80">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.vehicleStatus)"
              size="small"
            >
              {{ row.vehicleStatusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="verificationStatusName" label="认证状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getVerificationStatusType(row.verificationStatus)"
              size="small"
            >
              {{ row.verificationStatusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registrationTypeName" label="注册类型" width="100" />
        <el-table-column prop="parkingSpaceNo" label="关联车位" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleVerify(row)"
              v-if="row.verificationStatus === 0"
            >
              认证
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleStatusChange(row)"
            >
              状态
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑车辆对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input
            v-model="form.licensePlate"
            placeholder="请输入车牌号"
            maxlength="10"
          />
        </el-form-item>
        <el-form-item label="车辆类型" prop="vehicleType">
          <el-select
            v-model="form.vehicleType"
            placeholder="请选择车辆类型"
            style="width: 100%"
          >
            <el-option label="小型汽车" :value="1" />
            <el-option label="大型汽车" :value="2" />
            <el-option label="摩托车" :value="3" />
            <el-option label="电动车" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input
            v-model="form.brand"
            placeholder="请输入品牌"
          />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input
            v-model="form.model"
            placeholder="请输入型号"
          />
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-input
            v-model="form.color"
            placeholder="请输入颜色"
          />
        </el-form-item>
        <el-form-item label="注册类型" prop="registrationType">
          <el-select
            v-model="form.registrationType"
            placeholder="请选择注册类型"
            style="width: 100%"
          >
            <el-option label="业主车辆" :value="1" />
            <el-option label="租户车辆" :value="2" />
            <el-option label="访客车辆" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联车位" prop="parkingSpaceId">
          <el-select
            v-model="form.parkingSpaceId"
            placeholder="请选择车位"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="space in parkingSpaces"
              :key="space.id"
              :label="space.spaceNo"
              :value="space.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 认证对话框 -->
    <el-dialog
      v-model="verifyDialogVisible"
      title="车辆认证"
      width="500px"
    >
      <el-form
        ref="verifyFormRef"
        :model="verifyForm"
        :rules="verifyRules"
        label-width="100px"
      >
        <el-form-item label="车牌号">
          <el-input
            v-model="verifyForm.licensePlate"
            disabled
          />
        </el-form-item>
        <el-form-item label="认证材料" prop="verificationMaterials">
          <el-input
            v-model="verifyForm.verificationMaterials"
            type="textarea"
            placeholder="请输入认证材料说明"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="verifyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleVerifySubmit" :loading="verifyLoading">
          确定认证
        </el-button>
      </template>
    </el-dialog>

    <!-- 状态变更对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="变更车辆状态"
      width="400px"
    >
      <el-form
        ref="statusFormRef"
        :model="statusForm"
        :rules="statusRules"
        label-width="100px"
      >
        <el-form-item label="车牌号">
          <el-input
            v-model="statusForm.licensePlate"
            disabled
          />
        </el-form-item>
        <el-form-item label="车辆状态" prop="vehicleStatus">
          <el-select
            v-model="statusForm.vehicleStatus"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
            <el-option label="黑名单" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleStatusSubmit" :loading="statusLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Upload, Download } from '@element-plus/icons-vue'
import { showSuccess, showError } from '@/utils/message'

// 作者：Wu.Liang

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const verifyLoading = ref(false)
const statusLoading = ref(false)
const dialogVisible = ref(false)
const verifyDialogVisible = ref(false)
const statusDialogVisible = ref(false)
const dialogTitle = ref('')

// 静态数据
const allTableData = ref([
  {
    id: 1,
    licensePlate: '京A12345',
    vehicleType: 1,
    vehicleTypeName: '小型汽车',
    brand: '丰田',
    model: '凯美瑞',
    color: '白色',
    vehicleStatus: 1,
    vehicleStatusName: '正常',
    verificationStatus: 1,
    verificationStatusName: '已认证',
    registrationType: 1,
    registrationTypeName: '业主车辆',
    parkingSpaceId: 1,
    parkingSpaceNo: 'A-001',
    createTime: '2024-01-01 10:00:00',
    remark: ''
  },
  {
    id: 2,
    licensePlate: '京B67890',
    vehicleType: 1,
    vehicleTypeName: '小型汽车',
    brand: '本田',
    model: '雅阁',
    color: '黑色',
    vehicleStatus: 2,
    vehicleStatusName: '黑名单',
    verificationStatus: 0,
    verificationStatusName: '未认证',
    registrationType: 2,
    registrationTypeName: '租户车辆',
    parkingSpaceId: 2,
    parkingSpaceNo: 'A-002',
    createTime: '2024-01-02 11:00:00',
    remark: '违规停车'
  },
  {
    id: 3,
    licensePlate: '京C11111',
    vehicleType: 2,
    vehicleTypeName: '大型汽车',
    brand: '奔驰',
    model: 'S级',
    color: '银色',
    vehicleStatus: 1,
    vehicleStatusName: '正常',
    verificationStatus: 1,
    verificationStatusName: '已认证',
    registrationType: 1,
    registrationTypeName: '业主车辆',
    parkingSpaceId: 3,
    parkingSpaceNo: 'B-001',
    createTime: '2024-01-03 12:00:00',
    remark: ''
  },
  {
    id: 4,
    licensePlate: '京D22222',
    vehicleType: 3,
    vehicleTypeName: '摩托车',
    brand: '本田',
    model: 'CB400',
    color: '红色',
    vehicleStatus: 0,
    vehicleStatusName: '禁用',
    verificationStatus: 2,
    verificationStatusName: '认证失败',
    registrationType: 3,
    registrationTypeName: '访客车辆',
    parkingSpaceId: null,
    parkingSpaceNo: '',
    createTime: '2024-01-04 13:00:00',
    remark: '证件不齐全'
  },
  {
    id: 5,
    licensePlate: '京E33333',
    vehicleType: 4,
    vehicleTypeName: '电动车',
    brand: '雅迪',
    model: 'YADEA',
    color: '蓝色',
    vehicleStatus: 1,
    vehicleStatusName: '正常',
    verificationStatus: 1,
    verificationStatusName: '已认证',
    registrationType: 1,
    registrationTypeName: '业主车辆',
    parkingSpaceId: 4,
    parkingSpaceNo: 'C-001',
    createTime: '2024-01-05 14:00:00',
    remark: ''
  }
])

const parkingSpaces = ref([
  { id: 1, spaceNo: 'A-001' },
  { id: 2, spaceNo: 'A-002' },
  { id: 3, spaceNo: 'B-001' },
  { id: 4, spaceNo: 'C-001' },
  { id: 5, spaceNo: 'C-002' }
])

// 搜索表单
const searchForm = reactive({
  licensePlate: '',
  vehicleType: null as number | null,
  vehicleStatus: null as number | null,
  verificationStatus: null as number | null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const form = reactive({
  id: null,
  licensePlate: '',
  vehicleType: null,
  brand: '',
  model: '',
  color: '',
  registrationType: null,
  parkingSpaceId: null,
  remark: ''
})

// 认证表单
const verifyForm = reactive({
  vehicleId: null,
  licensePlate: '',
  verificationMaterials: ''
})

// 状态表单
const statusForm = reactive({
  vehicleId: null,
  licensePlate: '',
  vehicleStatus: null
})

// 表单校验规则
const rules = {
  licensePlate: [
    { required: true, message: '请输入车牌号', trigger: 'blur' },
    { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4}[A-Z0-9挂学警港澳]$/, message: '车牌号格式不正确', trigger: 'blur' }
  ],
  vehicleType: [
    { required: true, message: '请选择车辆类型', trigger: 'change' }
  ],
  brand: [
    { required: true, message: '请输入品牌', trigger: 'blur' }
  ],
  registrationType: [
    { required: true, message: '请选择注册类型', trigger: 'change' }
  ]
}

const verifyRules = {
  verificationMaterials: [
    { required: true, message: '请输入认证材料说明', trigger: 'blur' }
  ]
}

const statusRules = {
  vehicleStatus: [
    { required: true, message: '请选择车辆状态', trigger: 'change' }
  ]
}

// 表单引用
const formRef = ref()
const verifyFormRef = ref()
const statusFormRef = ref()

// 过滤后的表格数据
const filteredTableData = computed(() => {
  let filtered = [...allTableData.value]
  
  // 车牌号过滤
  if (searchForm.licensePlate) {
    filtered = filtered.filter(item => 
      item.licensePlate.toLowerCase().includes(searchForm.licensePlate.toLowerCase())
    )
  }
  
  // 车辆类型过滤
  if (searchForm.vehicleType !== null) {
    filtered = filtered.filter(item => item.vehicleType === searchForm.vehicleType)
  }
  
  // 车辆状态过滤
  if (searchForm.vehicleStatus !== null) {
    filtered = filtered.filter(item => item.vehicleStatus === searchForm.vehicleStatus)
  }
  
  // 认证状态过滤
  if (searchForm.verificationStatus !== null) {
    filtered = filtered.filter(item => item.verificationStatus === searchForm.verificationStatus)
  }
  
  // 更新分页总数
  pagination.total = filtered.length
  
  // 分页
  const start = (pagination.current - 1) * pagination.size
  const end = start + pagination.size
  return filtered.slice(start, end)
})

// 生命周期
onMounted(() => {
  pagination.total = allTableData.value.length
})

// 方法定义
const handleSearch = () => {
  pagination.current = 1
      showSuccess('搜索完成')
}

const handleReset = () => {
  Object.assign(searchForm, {
    licensePlate: '',
    vehicleType: null,
    vehicleStatus: null,
    verificationStatus: null
  })
  pagination.current = 1
  showSuccess('重置完成')
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
}

const handleAdd = () => {
  dialogTitle.value = '添加车辆'
  Object.assign(form, {
    id: null,
    licensePlate: '',
    vehicleType: null,
    brand: '',
    model: '',
    color: '',
    registrationType: null,
    parkingSpaceId: null,
    remark: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  dialogTitle.value = '编辑车辆'
  Object.assign(form, {
    id: row.id,
    licensePlate: row.licensePlate,
    vehicleType: row.vehicleType,
    brand: row.brand,
    model: row.model,
    color: row.color,
    registrationType: row.registrationType,
    parkingSpaceId: row.parkingSpaceId,
    remark: row.remark
  })
  dialogVisible.value = true
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该车辆吗？', '提示', {
      type: 'warning'
    })
    
    // 从静态数据中删除
    const index = allTableData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      allTableData.value.splice(index, 1)
    }
    
    showSuccess('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      showError('删除失败')
    }
  }
}

const handleVerify = (row: any) => {
  Object.assign(verifyForm, {
    vehicleId: row.id,
    licensePlate: row.licensePlate,
    verificationMaterials: ''
  })
  verifyDialogVisible.value = true
}

const handleStatusChange = (row: any) => {
  Object.assign(statusForm, {
    vehicleId: row.id,
    licensePlate: row.licensePlate,
    vehicleStatus: row.vehicleStatus
  })
  statusDialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
          if (form.id) {
        // 更新现有车辆
        const index = allTableData.value.findIndex(item => item.id === form.id)
        if (index !== -1 && form.vehicleType && form.registrationType) {
          const vehicleTypeName = ['', '小型汽车', '大型汽车', '摩托车', '电动车'][form.vehicleType]
          const registrationTypeName = ['', '业主车辆', '租户车辆', '访客车辆'][form.registrationType]
          const parkingSpace = parkingSpaces.value.find(space => space.id === form.parkingSpaceId)
          
          Object.assign(allTableData.value[index], {
            ...form,
            vehicleTypeName,
            registrationTypeName,
            parkingSpaceNo: parkingSpace?.spaceNo || ''
          })
        }
        showSuccess('更新成功')
      } else {
        // 添加新车辆
        if (form.vehicleType && form.registrationType) {
          const newVehicle = {
            id: allTableData.value.length + 1,
            ...form,
            vehicleTypeName: ['', '小型汽车', '大型汽车', '摩托车', '电动车'][form.vehicleType],
            vehicleStatus: 1,
            vehicleStatusName: '正常',
            verificationStatus: 0,
            verificationStatusName: '未认证',
            registrationTypeName: ['', '业主车辆', '租户车辆', '访客车辆'][form.registrationType],
            parkingSpaceNo: parkingSpaces.value.find(space => space.id === form.parkingSpaceId)?.spaceNo || '',
            createTime: new Date().toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit'
            }).replace(/\//g, '-')
          }
          allTableData.value.unshift(newVehicle)
          showSuccess('添加成功')
        }
      }
    
    dialogVisible.value = false
  } catch (error) {
    showError('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleVerifySubmit = async () => {
  try {
    await verifyFormRef.value.validate()
    verifyLoading.value = true
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新认证状态
    const index = allTableData.value.findIndex(item => item.id === verifyForm.vehicleId)
    if (index !== -1) {
      allTableData.value[index].verificationStatus = 1
      allTableData.value[index].verificationStatusName = '已认证'
    }
    
    showSuccess('认证成功')
    verifyDialogVisible.value = false
  } catch (error) {
    showError('认证失败')
  } finally {
    verifyLoading.value = false
  }
}

const handleStatusSubmit = async () => {
  try {
    await statusFormRef.value.validate()
    statusLoading.value = true
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新车辆状态
    const index = allTableData.value.findIndex(item => item.id === statusForm.vehicleId)
    if (index !== -1) {
      const statusNames = ['禁用', '正常', '黑名单']
      allTableData.value[index].vehicleStatus = statusForm.vehicleStatus
      allTableData.value[index].vehicleStatusName = statusNames[statusForm.vehicleStatus]
    }
    
    showSuccess('状态更新成功')
    statusDialogVisible.value = false
  } catch (error) {
    showError('状态更新失败')
  } finally {
    statusLoading.value = false
  }
}

const handleDialogClose = () => {
  formRef.value?.resetFields()
}

const handleBatchImport = () => {
  showSuccess('批量导入功能已执行，成功导入10条数据')
}

const handleExport = () => {
  showSuccess('导出功能已执行，文件已下载到本地')
}

const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'danger'
    case 1: return 'success'
    case 2: return 'warning'
    default: return 'info'
  }
}

const getVerificationStatusType = (status: number) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}
</script>

<style scoped>
.vehicle-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.action-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 